<?php
/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\model;

class MessageModel extends BaseModel
{
    protected $table = 'message';

    /**
     * 消息类型常量
     */
    const TYPE_LIKE = 1;        // 点赞
    const TYPE_FAVORITE = 2;    // 收藏
    const TYPE_COMMENT = 3;     // 评论
    const TYPE_FOLLOW = 4;      // 关注
    const TYPE_SYSTEM = 9;      // 系统消息

    /**
     * 消息类型映射
     *
     * @var array
     */
    public static array $typeMap = [
        self::TYPE_LIKE => '点赞',
        self::TYPE_FAVORITE => '收藏',
        self::TYPE_COMMENT => '评论',
        self::TYPE_FOLLOW => '关注',
        self::TYPE_SYSTEM => '系统消息',
    ];

    /**
     * 属性类型转换
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp',
        'type' => 'integer',
        'is_read' => 'integer',
    ];

    /**
     * 可批量赋值的属性
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'to_user_id',
        'post_id',
        'content',
        'type',
        'is_read'
    ];

    /**
     * 发送用户关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(UsersModel::class, 'user_id');
    }

    /**
     * 接收用户关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function toUser()
    {
        return $this->belongsTo(UsersModel::class, 'to_user_id');
    }

    /**
     * 相关帖子关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function post()
    {
        return $this->belongsTo(PostModel::class, 'post_id');
    }

    /**
     * 获取消息类型文本
     *
     * @return string
     */
    public function getTypeTextAttribute(): string
    {
        return self::$typeMap[$this->type] ?? '未知类型';
    }

    /**
     * 根据类型获取消息类型文本
     *
     * @param int $type
     * @return string
     */
    public static function getTypeText(int $type): string
    {
        return self::$typeMap[$type] ?? '未知类型';
    }

    /**
     * 获取所有消息类型
     *
     * @return array
     */
    public static function getAllTypes(): array
    {
        return self::$typeMap;
    }
}